import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const state = {
  datePointer: {
    value: '',
    format: ''
  },
  count: 100,
  author: 'lxf',
  days: [],
  todos: [
    {id: 1, text: '...', done: true},
    {id: 2, text: '...', done: false},
    {id: 3, text: '...', done: true},
    {id: 4, text: '...', done: true},
    {id: 5, text: '...', done: false}
  ]
};
const getters = {
  doneTodos: state => {
    return state.todos.filter(todo => todo.done).length
  }
};

const mutations = {
  increment (state) {
    // 变更状态
    state.count++
  },
  ['SET_ARTICLES'] (state, date, arr) {
    state.days.push({
      date: date,
      articles: arr
    })
  },
  ['SET_DATE_POINTER'] (state, value) {
    state.datePointer = value
  },
  ['SET_THEMES'] (state, arr) {
    state.themes = arr
  }
};

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions: {
    increment (context) {
      context.commit('increment')
    },
    actionA ({commit}) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          commit('someMutation')
          resolve()
        }, 1000)
      })
    },
    checkout ({commit, state}, products) {
      const savedCartItems = [...state.cart.added]
      commit(types.CHECKOUT_REQUEST)
      shop.buyProducts(
        products,
        // 成功操作
        () => commit(types.CHECKOUT_SUCCESS),
        // 失败操作
        () => commit(types.CHECKOUT_FAILURE, savedCartItems)
      )
    }
  },
  strict: true
})
